<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use DB;
use Cache;
use Illuminate\Support\Facades\Redis;

class ChuApiController extends Controller
{
    //通过apiKey获取token，并设置有效期
    public function getToken() {

        if(request()->expectsJson()) {
            $key = request()->header('Access-Key', '');
            $dbKey = DB::Table('setting_sys')->where('key', 'apiKey')->value('value');
            if(!$key || ($key != $dbKey)) {
                return out(0, 'key错误！');
            }
            $redis = Redis::connection('public');
            $data = [];
            $rootUrl = request()->root();
            $ip = request()->ip();
            $key = 'apiToken'.$rootUrl.$ip;
            $tokenR = $redis->get($key);
            if(!$tokenR) {
                $time = time();
                $str = $key.$time.$rootUrl.$ip;
                $token = md5($str);
                if($redis->set($key, $token, 'EX', 72*3600)) {
                    $tokenR = $token;
                }
            }
            $data['token'] = $tokenR;
            $code = $tokenR ? 1 : 0;
            return out($code, 'success', $data);
        }
    }
}
